<?php


namespace app\controller;

use app\model\User as UserModel;
use app\model\UserInfo;
use app\model\UserRole;
use \app\traits\CommonTrait as Response;
use app\BaseController;
use GuzzleHttp\Client;
use think\facade\Log;
use weixin\WXBizDataCrypt;

class User extends BaseController
{
    use Response;

    /**
     * 登录注册
     * @return \think\response\Json
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function regLogin(){
        $code = request()->param('code', '');
        $encryptedData = request()->param('encryptedData', '');
        $iv = request()->param('iv', '');
        $avatarUrl = request()->param('avatarUrl', '');
        $nickName = request()->param('nickName', '');
        $province = request()->param('province', '');
        $city = request()->param('city', '');

        if($code == '') return $this->apiJson(-1, '缺少参数');
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $data = [
            'appid' => config('app.mp.appid'),
            'secret' => config('app.mp.secret'),
            'js_code' => $code,
            'grant_type'=> 'grant_type'
        ];

        $client = new Client();

        $response = $client->request('GET', $url, ['query'=>$data,'timeout'=>30, 'verify' => false]);
        $result = json_decode($response->getBody()->getContents(), true);

        //获取成功
        $info = [];
        if(!isset($result['errcode'])){
            $phone = $this->phone($data['appid'], $encryptedData, $iv, $result['session_key']);
            $user = UserModel::field('id,name,head_img,desc,phone,douyin,author_id,token,invite_uid,team_id,company_id,invite_code,is_system,status,create_time,update_time')
//                ->where(['wx_unid'=>$result['unionid']])
                ->where(['phone'=>$phone])
                ->find();
            $user_id = '';

            if($user){
                $user_id = $user['id'];
                $re = UserInfo::wxInfo($user_id, $result);
            }else{
                if($phone == '') return $this->apiJson(-1, '未绑定手机号');
                //判断用户信息表是否存在
                $res = UserInfo::where(['openid'=>$result['openid']])->find();
                if(!$res){
                    //不存在先添加到用户表，再添加到用户信息表
                    $r = UserModel::insert(['phone'=>$phone,'create_time'=>time(),'update_time'=>time()], true);
                    if($r){
                        $re = UserInfo::wxInfo($r, $result);
                        $user_id = $r;
                        $user = UserModel::field('id,name,head_img,desc,phone,douyin,author_id,token,invite_uid,team_id,company_id,invite_code,is_system,status,create_time,update_time')->find($user_id);
                    }
                }else{
                    return $this->apiJson(-1, '微信绑定手机号不匹配!');
                }
            }

            if($re){
                //生成token信息
                $roles = UserRole::field('rid')->where(['uid'=>$user_id])->select();
                if($roles){
                    $roles = $roles->toArray();
                    $roles = array_reduce($roles, function ($result, $value) {
                        return array_merge($result, array_values($value));
                    }, array());
                }
                $token = generate_token($user,$roles);
                $user->save(['token'=>$token,'wx_head_img'=>$avatarUrl,'wx_nickname'=>$nickName]);

                if($user){
                    $user = $user->toArray();
                    //默认达人身份
                    $user['role'] = 5;
                    $user['roles'] = $roles;
                }

                return $this->apiJson(1, 'ok', $user);
            }else{
                return $this->apiJson(-1, '绑定信息不合法!');
            }
        }else{
            return $this->apiJson(-1, '绑定信息不合法!');
        }
    }

    /**
     * 获取手机号
     * @param $appid
     * @param $encryptedData
     * @param $iv
     * @param $session_key
     */
    protected function phone($appid,$encryptedData,$iv,$session_key){
        $pc = new WXBizDataCrypt($appid, $session_key);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            $data = json_decode($data, true);
            return $data['phoneNumber'];
        } else {
            return '';
        }
    }

    /**
     * 修改手机号绑定
     * @return \think\response\Json
     */
    public function cgp(){
        $newPhone = request()->param('phone', '');
        $code = request()->param('code', '');
        $type = request()->param('type', 0);
        if($newPhone == '' || $code == '' || !$type) return $this->apiJson(-1, '缺少参数');
        if(!isMobile($newPhone)){
            return $this->apiJson(-1, '手机格式不对!');
        }
        if(!checkCode($newPhone,$type,$code)){
            return $this->apiJson(-1, '验证码不正确!');
        }
        $res = UserModel::changePhone($newPhone);
        if($res){
            return $this->apiJson(1 , '修改成功!');
        }else{
            return $this->apiJson(-1, '修改失败');
        }
    }

}